<template>
  <div>
    <!-- 按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0px" @click="showDialog">添加</el-button>
    <!-- 表格组件 -->
    <!-- 
      border:给表格添加纵向边框
      lable:显示的标题
      width:列的宽度
      align:标题的对齐方式
    -->
    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" label="序号" width="80px" align="center" :index="getIndex"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template v-slot="{ row, column, $index }">
          <!-- 
            row:每一列的数据
            column:table的总数据
           -->
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template v-slot="{ row, column, $index }">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger " icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- 
      current-page:当前页
      page-size:每页展示的条数
      total:总页数
      pager-count:连续的页数
      @size-change="handleSizeChange" @current-change="handleCurrentChange"
     -->
    <el-pagination :current-page="page" :page-sizes="[3, 5, 10]" :page-size="limit" :total="total" style="margin-top: 25px; text-align: center" layout=" prev, pager, next, jumper,->,sizes,total" @size-change="handleSizeChange" @current-change="handleCurrentChange"> </el-pagination>
    <!-- 对话框 -->
    <!-- 
      visible.sync:控制对话框的显示与隐藏
      rules:表单验证规则
     -->
    <el-dialog :title="form.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
      <el-form :model="form" style="width: 80%" :rules="rules" ref="formName">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="form.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- 
            action:设置图片上传的URL
            on-success:图片上传成功，执行
            before-upload:图片上传之前执行
           -->
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: 1, //当前的页
      limit: 3, //每页的展示条数
      total: 0, //总的页数
      list: [], //列表的数据
      dialogFormVisible: false, //对话框的显示与隐藏
      imageUrl: '', //上传图片的使用属性
      form: {
        tmName: '', //品牌的名字
        logoUrl: '', //品牌的图片
      }, //收集品牌的信息
      //表单的验证规则
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2到 10 个字符', trigger: 'blur' },
        ],
        logoUrl: [{ required: true, message: '请选择品牌的图片', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getPageList()
  },
  methods: {
    async getPageList() {
      let res = await this.$api.trademark.reqTradeMark({ page: this.page, limit: this.limit })
      if (res.code == 20000 || res.code === 200) {
        this.total = res.data.total
        this.list = res.data.records
      }
    },
    handleCurrentChange(page) {
      //修改参数
      this.page = page
      //重新发送请求
      this.getPageList()
    },
    handleSizeChange(pageszie) {
      this.limit = pageszie
      this.getPageList()
    },
    getIndex(index) {
      return index + 1 + (this.page - 1) * this.limit
    },
    //添加品牌
    showDialog() {
      this.dialogFormVisible = true
      // 清空数据
      this.form = { tmName: '', logoUrl: '' }
    },
    //修改品牌名称
    async updateTradeMark(row) {
      this.dialogFormVisible = true
      // this.form = row  //将服务器返回的数据直接给form表单，造成修改时不点击确定和取消就直接修改
      this.form = { ...row }
    },
    // 上传图片的回调函数
    //1.图片上传成功
    handleAvatarSuccess(res, file) {
      // res:上传成功服务器返回的图片的地址
      //file:上传成功服务器返回的图片的地址(res，file是一样的)
      // 收集品牌的图片数据，将来带给服务器
      // this.imageUrl=res.data(与下面是一样的)
      this.form.logoUrl = URL.createObjectURL(file.raw)
    },
    //2.图片上前之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 确定并隐藏对话框（按钮：有添加和修改的功能）
    addOrUpdateTradeMark() {
      this.$refs.formName.validate(async (valid) => {
        if (valid) {
          //符合验证规则
          // 添加数据
          if (!this.form.id) {
            let res = await this.$api.trademark.reqAddTradeMark(this.form)
            if (res.code == 200) {
              this.$message({ message: '添加成功', type: 'success' })
              // 添加成功，就返回到添加成功的数据也
              this.page = Math.ceil((this.total + 1) / this.limit)
              this.getPageList()
            }
          } else {
            //修改数据
            let res = await this.$api.trademark.reqUpdaeTradeMark(this.form)
            if (res.code == 200) {
              this.$message({ message: '修改成功', type: 'success' })
              this.getPageList()
            }
          }
          this.dialogFormVisible = false
        } else {
          //不符合验证规则
          return false
        }
      })
    },
    //删除品牌
    deleteTradeMark(row) {
      this.$confirm(`你确定删除${row.tmName}品牌吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await this.$api.trademark.reqDeleteTradeMark({ id: row.id })
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          }
          this.page = this.list > 1 ? this.page : this.page - 1
          this.getPageList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>